<?php
include_once 'data.php';
include_once 'functions.php';

$microtime1 = microtime(true);

function search_row($field) {

	print '
<input type="text" size="70" style="width:99.5%" name="'.$field.'" value="'.(isset($_SESSION['session_'.$field]) ? htmlspecialchars($_SESSION['session_'.$field]) : '').'">
<table border=0 cellspacing=0 cellpadding=0>
 <tr>
  <td class="select_span" style="line-height:16px">
   <input type="radio" name="'.$field.'_separator" value="AND" style="display:none" '.((isset($_SESSION['session_'.$field.'_separator']) && $_SESSION['session_'.$field.'_separator'] == 'AND') ? 'checked' : '').'>
   <span class="ui-icon ui-icon-radio-'.((isset($_SESSION['session_'.$field.'_separator']) && $_SESSION['session_'.$field.'_separator'] == 'AND') ? 'off' : 'on').'" style="float:left">
   </span>all of the words (AND)&nbsp;
  </td>
  <td class="select_span" style="line-height:16px">
   <input type="radio" name="'.$field.'_separator" value="OR" style="display:none" '.((isset($_SESSION['session_'.$field.'_separator']) && $_SESSION['session_'.$field.'_separator'] == 'OR') ? 'checked' : '').'>
   <span class="ui-icon ui-icon-radio-'.((isset($_SESSION['session_'.$field.'_separator']) && $_SESSION['session_'.$field.'_separator'] == 'OR') ? 'off' : 'on').'" style="float:left">
   </span>at least one of the words (OR)&nbsp;
  </td>
  <td class="select_span" style="line-height:16px">
   <input type="radio" name="'.$field.'_separator" value="PHRASE" style="display:none" '.((!isset($_SESSION['session_'.$field.'_separator']) || $_SESSION['session_'.$field.'_separator'] == 'PHRASE') ? 'checked' : '').'>
   <span class="ui-icon ui-icon-radio-'.((!isset($_SESSION['session_'.$field.'_separator']) || $_SESSION['session_'.$field.'_separator'] == 'PHRASE') ? 'off' : 'on').'" style="float:left">
   </span>the exact phrase
  </td>
 </tr>
</table>';

}

if (isset($_GET['newsearch'])) {
	unset($_SESSION['session_anywhere']);
	unset($_SESSION['session_anywhere_separator']);
	unset($_SESSION['session_authors']);
	unset($_SESSION['session_authors_separator']);
	unset($_SESSION['session_journal']);
	unset($_SESSION['session_journal_separator']);
	unset($_SESSION['session_title']);
	unset($_SESSION['session_title_separator']);
	unset($_SESSION['session_abstract']);
	unset($_SESSION['session_abstract_separator']);
	unset($_SESSION['session_keywords']);
	unset($_SESSION['session_keywords_separator']);
	unset($_SESSION['session_secondary_title']);
	unset($_SESSION['session_secondary_title_separator']);
	unset($_SESSION['session_affiliation']);
	unset($_SESSION['session_affiliation_separator']);
	unset($_SESSION['session_search_id']);
	unset($_SESSION['session_year']);
	unset($_SESSION['session_fulltext']);
	unset($_SESSION['session_fulltext_separator']);
        unset($_SESSION['session_notes']);
	unset($_SESSION['session_notes_separator']);
	unset($_SESSION['session_category']);
	unset($_SESSION['session_whole_words']);
	unset($_SESSION['session_case']);
        unset($_SESSION['rating[]']);
	die();
}

if (isset($_GET['savesearch']) && !empty($_GET['searchname'])) {

	database_connect($database_path, 'library');
    
	$stmt = $dbHandle->prepare("DELETE FROM searches WHERE userID=:user AND searchname=:searchname");

	$stmt->bindParam(':user', $user, PDO::PARAM_STR);
	$stmt->bindParam(':searchname', $searchname, PDO::PARAM_STR);

	$stmt2 = $dbHandle->prepare("INSERT INTO searches (userID,searchname,searchfield,searchvalue) VALUES (:user,:searchname,:searchfield,:searchvalue)");

	$stmt2->bindParam(':user', $user, PDO::PARAM_STR);
	$stmt2->bindParam(':searchname', $searchname, PDO::PARAM_STR);
	$stmt2->bindParam(':searchfield', $searchfield, PDO::PARAM_STR);
	$stmt2->bindParam(':searchvalue', $searchvalue, PDO::PARAM_STR);

	$dbHandle->beginTransaction();

	$user = intval($_SESSION['user_id']);
	$searchname = 'advancedsearch#'.trim($_GET['searchname']);

	$stmt->execute();

       unset($_GET['_']);
       unset($_GET['savesearch']);
       unset($_GET['searchname']);
	reset($_GET);
	while (list($key, $field) = each($_GET)) {
		if (is_array($_GET[$key])) {
			while (list(, $value2) = each($_GET[$key])) {
				$searchfield = $key.'[]';
				$searchvalue = $value2;
				$stmt2->execute();			}
		} elseif ($key != 'from' && $key != 'limit' && $key != 'display' && $key != 'orderby' && !empty($_GET[$key])) {
			$searchfield = $key;
			$searchvalue = $field;
			$stmt2->execute();
		}
	}

	$dbHandle->commit();
	die();
}

if (isset($_GET['loadsearch']) && !empty($_GET['searchname'])) {

	database_connect($database_path, 'library');

	$stmt = $dbHandle->prepare("SELECT searchfield,searchvalue FROM searches WHERE userID=:user AND searchname=:searchname");

	$stmt->bindParam(':user', $user, PDO::PARAM_STR);
	$stmt->bindParam(':searchname', $searchname, PDO::PARAM_STR);

	$user = $_SESSION['user_id'];
	$searchname = "advancedsearch#".trim($_GET['searchname']);

	$stmt->execute();

	$url_string_array = array ();

	while ($search = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$url_string_array[] = urlencode($search['searchfield']).'='.urlencode($search['searchvalue']);
	}
	$url_string = join ('&',$url_string_array);
	die($url_string);
}

if (isset($_GET['deletesearch']) && !empty($_GET['searchname'])) {

	database_connect($database_path, 'library');
    
	$stmt = $dbHandle->prepare("DELETE FROM searches WHERE userID=:user AND searchname=:searchname");

	$stmt->bindParam(':user', $user, PDO::PARAM_STR);
	$stmt->bindParam(':searchname', $searchname, PDO::PARAM_STR);

	$user = $_SESSION['user_id'];
	$searchname = "advancedsearch#".trim($_GET['searchname']);

	$stmt->execute();

	die('OK');
}

if (isset($_GET['renamesearch']) && !empty($_GET['searchname']) && !empty($_GET['searchname2'])) {

	database_connect($database_path, 'library');
    
	$stmt = $dbHandle->prepare("UPDATE searches SET searchname=:searchname2 WHERE userID=:user AND searchname=:searchname");

	$stmt->bindParam(':user', $user, PDO::PARAM_STR);
	$stmt->bindParam(':searchname', $searchname, PDO::PARAM_STR);
	$stmt->bindParam(':searchname2', $searchname2, PDO::PARAM_STR);

	$user = $_SESSION['user_id'];
	$searchname = "advancedsearch#".trim(urldecode($_GET['searchname']));
	$searchname2 = "advancedsearch#".trim(urldecode($_GET['searchname2']));

	$stmt->execute();

	die('OK');
}

database_connect($database_path, 'library');

$shelf_files = array();
$shelf_files = read_shelf($dbHandle);

$desktop_projects = array();
$desktop_projects = read_desktop($dbHandle);

$dbHandle = null;

if (!isset($_GET['project'])) {
        $project = '';
    } else {
        $project = $_GET['project'];
    }

    if (!isset($_SESSION['limit'])) {
        $limit = 10;
    } else {
        settype($_SESSION['limit'], "integer");
        $limit = $_SESSION['limit'];
    }

    if (!isset($_SESSION['orderby'])) {
        $orderby = 'id';
    } else {
        $orderby = $_SESSION['orderby'];
    }

    if (!isset($_SESSION['display'])) {
        $display = 'summary';
    } else {
        $display = $_SESSION['display'];
    }

if (!isset($_GET['from'])) {
	$from = '0';
} else {
	settype($_GET['from'], "integer");
	$from = $_GET['from'];
}

if (	empty($_GET['select']) ||
	($_GET['select'] != 'library' &&
	$_GET['select'] != 'shelf' &&
	$_GET['select'] != 'desk' &&
	$_GET['select'] != 'clipboard')) {

	$_GET['select'] = 'library';
}

if (!empty($_GET['anywhere']) || !empty($_GET['authors']) || !empty($_GET['title']) || !empty($_GET['journal']) ||
	!empty($_GET['abstract']) || !empty($_GET['keywords']) || !empty($_GET['year']) || !empty($_GET['fulltext']) ||
        !empty($_GET['notes']) || !empty($_GET['secondary_title']) || !empty($_GET['affiliation']) || !empty($_GET['search_id'])) {

    ######### LIMITS ################

    database_connect($database_path, 'library');

        $rating_search = '';
        $rating_searches = array ();

	if (!isset($_GET['rating'])) {
		$_GET['rating'][] = 1;
		$_GET['rating'][] = 2;
		$_GET['rating'][] = 3;
	} else {
		$ratings = array (1, 2, 3);
		$missing_ratings = array_diff ($ratings, $_GET['rating']);
		foreach ($missing_ratings as $missing_rating) {
			$rating_searches[] = 'rating!='.intval($missing_rating);
		}
		if (!empty($rating_searches)) {
			$rating_search = join (' AND ', $rating_searches);
			$rating_search = $rating_search.' AND ';
		}
	}

	$category_search = '';

	if (isset($_GET['category']) && $_GET['category'] != 'all' && $_GET['category'] != '0') {
            $result = $dbHandle->query("SELECT fileID FROM filescategories WHERE categoryID=".intval($_GET['category']));
            $category_array = $result->fetchAll(PDO::FETCH_COLUMN);
            $category_string = implode (',', $category_array);
            $category_search = "id IN (".$category_string.") AND ";
            $category_array = null;
            $result = null;
	} elseif (isset($_GET['category']) && $_GET['category'] == '0') {
            $result = $dbHandle->query("SELECT id FROM library WHERE id NOT IN (SELECT fileID FROM filescategories)");
            $category_array = $result->fetchAll(PDO::FETCH_COLUMN);
            $category_string = implode (',', $category_array);
            $category_search = "id IN (".$category_string.") AND ";
            $category_array = null;
            $result = null;
	}

        $in = '';

	if ($_GET['select'] == 'shelf') {
		$in = join (",", $shelf_files);
		$in = "id IN ($in) AND";
	}

	if ($_GET['select'] == 'clipboard') {
		$in = "id IN () AND";
		if (!empty($_SESSION['session_clipboard'])) {
			$clipboard_files = join (",", $_SESSION['session_clipboard']);
			$in = "id IN ($clipboard_files) AND";
		}
	}

	if ($_GET['select'] == 'desk' && is_numeric($_GET['project'])) {

            $result = $dbHandle->query("SELECT fileID FROM projectsfiles WHERE projectID=".intval($_GET['project']));
            $project_files = $result->fetchAll(PDO::FETCH_COLUMN);
            $project_files = implode (',', $project_files);
            $in = "id IN (".$project_files.") AND ";
            $result = null;
            $result = $dbHandle->query("SELECT project FROM projects WHERE projectID=".intval($_GET['project']));
            $project_name = $result->fetchColumn();
            $result = null;
	}

	if (isset($orderby) && ($orderby == 'year' || $orderby == 'addition_date' || $orderby == 'rating' || $orderby == 'id')) {
		$ordering = 'DESC';
	} else {
		$ordering = 'ASC';
	}

	######### store search hash ###########
	$md5_query = '';
        unset($_GET['_']);
	$_GET['orderby'] = $orderby;
	ksort($_GET);

	while (list($key, $value) = each($_GET)) {
		if (is_array($_GET[$key])) {
			while (list(, $value2) = each($_GET[$key])) {
				if (!empty($value2)) $md5_query .= $key.$value2;
			}
		} elseif ($key != 'from' && $key != 'limit' && $key != 'display' && !empty($value)) $md5_query .= $key.$value;
	}
	$md5_query = md5($md5_query);

	######## REGISTER SESSION VARIABLES ##############

	$get_array = array ('anywhere','authors','affiliation','title','journal','secondary_title','abstract','keywords',
            'year','fulltext','notes','category','whole_words','case','rating','search_id');

	while (list($key, $index) = each($get_array)) {

		if (isset($_GET[$index]) && !empty($_GET[$index])) {

			${$index} = $_GET[$index];
			$_SESSION['session_'.$index] = $_GET[$index];

			if ($index != 'category' && $index != 'year' && $index != 'whole_words' && $index != 'case' && $index != 'rating' && $index != 'search_id') {

				${$index} = $_GET[$index];
				${$index.'_separator'} = $_GET[$index.'_separator'];
				$_SESSION['session_'.$index.'_separator'] = $_GET[$index.'_separator'];
			}
		} else {

			${$index} = '';
			unset($_SESSION['session_'.$index]);

			if ($index != 'category' && $index != 'year' && $index != 'whole_words' && $index != 'case' && $index != 'rating' && $index != 'search_id') {
				${$index.'_separator'} = '';
				unset($_SESSION['session_'.$index.'_separator']);
			}
		}
	}

	$anywhere_array = array();
	$authors_array = array();
	$title_array = array();
	$journal_array = array();
	$secondary_title_array = array();
	$abstract_array = array();
	$keywords_array = array();
	$affiliation_array = array();
	$search_id_array = array();
	$year_array = array();
	$fulltext_array = array();
        $notes_array = array();
	$case2 = $case;
	if (empty($case)) $case2 = 0;
	$rating_array = array();
	database_connect($database_path, 'library');

	#######################################################################

	if (!empty($_GET['anywhere']) && $_GET['searchtype'] == 'metadata') {

		$anywhere_array = array ($_GET['anywhere']);
		if ($_GET['anywhere_separator'] == 'AND' || $_GET['anywhere_separator'] == 'OR') $anywhere_array = explode(' ', $_GET['anywhere']);

		while ($anywhere = each($anywhere_array)) {

			$like_query = str_replace("\\", "\\\\", $anywhere[1]);
			$like_query = str_replace("%", "\%", $like_query);
			$like_query = str_replace("_", "\_", $like_query);
			$like_query = str_replace("<*>", "%", $like_query);
			$like_query = str_replace("<?>", "_", $like_query);

			$regexp_query = addcslashes($anywhere[1],"\044\050..\053\056\057\074\076\077\133\134\136\173\174");
			$regexp_query = str_replace('\<\*\>', '.*', $regexp_query);
			$regexp_query = str_replace('\<\?\>', '.?', $regexp_query);

			$like_query = $dbHandle->quote("%$like_query%");
			$regexp_query = str_replace("'", "''", $regexp_query);

			$translation = utf8_deaccent($anywhere[1]);

			if ($translation != $anywhere[1]) {

				$like_query_translated = $dbHandle->quote("%$translation%");
				$regexp_query_translated = str_replace("'", "''", $translation);

				$like_sql = "authors LIKE $like_query ESCAPE '\' OR journal LIKE $like_query ESCAPE '\' OR secondary_title LIKE $like_query ESCAPE '\' OR affiliation LIKE $like_query ESCAPE '\' OR title LIKE $like_query ESCAPE '\' OR abstract LIKE $like_query ESCAPE '\' OR year LIKE $like_query ESCAPE '\' OR id LIKE $like_query ESCAPE '\' OR keywords LIKE $like_query ESCAPE '\' OR
						authors_ascii LIKE $like_query_translated ESCAPE '\' OR title_ascii LIKE $like_query_translated ESCAPE '\' OR abstract_ascii LIKE $like_query_translated ESCAPE '\'";

				$regexp_sql = "regexp_match(authors, '$regexp_query', $case2) OR regexp_match(journal, '$regexp_query', $case2) OR regexp_match(secondary_title, '$regexp_query', $case2) OR regexp_match(affiliation, '$regexp_query', $case2) OR regexp_match(title, '$regexp_query', $case2) OR
						regexp_match(abstract, '$regexp_query', $case2) OR regexp_match(year, '$regexp_query', $case2) OR regexp_match(keywords, '$regexp_query', $case2) OR
						regexp_match(authors_ascii, '$regexp_query_translated', $case2) OR regexp_match(title_ascii, '$regexp_query_translated', $case2) OR regexp_match(abstract_ascii, '$regexp_query_translated', $case2)";
			} else {

				$like_sql = "authors_ascii LIKE $like_query ESCAPE '\' OR journal LIKE $like_query ESCAPE '\' OR secondary_title LIKE $like_query ESCAPE '\' OR affiliation LIKE $like_query ESCAPE '\' OR title_ascii LIKE $like_query ESCAPE '\' OR abstract_ascii LIKE $like_query ESCAPE '\' OR year LIKE $like_query ESCAPE '\' OR id LIKE $like_query ESCAPE '\' OR keywords LIKE $like_query ESCAPE '\'";
				$regexp_sql = "regexp_match(authors_ascii, '$regexp_query', $case2) OR regexp_match(journal, '$regexp_query', $case2) OR regexp_match(secondary_title, '$regexp_query', $case2) OR regexp_match(affiliation, '$regexp_query', $case2) OR regexp_match(title_ascii, '$regexp_query', $case2) OR
						regexp_match(abstract_ascii, '$regexp_query', $case2) OR regexp_match(year, '$regexp_query', $case2) OR regexp_match(keywords, '$regexp_query', $case2)";
			}

			if ($whole_words == 1) {
				$anywhere_regexp[] = '('.$like_sql.') AND ('.$regexp_sql.')';
			} else {
				$anywhere_regexp[] = '('.$like_sql.')';
			}
		}

		if ($_GET['anywhere_separator'] == 'AND') $search_string[] = join (' AND ', $anywhere_regexp);
		if ($_GET['anywhere_separator'] == 'OR') $search_string[] = join (' OR ', $anywhere_regexp);
		if ($_GET['anywhere_separator'] == 'PHRASE') $search_string[] =  join ('', $anywhere_regexp);
	}

	#######################################################################

	if (!empty($_GET['authors']) && $_GET['searchtype'] == 'metadata') {

		$authors_array = array ($_GET['authors']);
		if ($_GET['authors_separator'] == 'AND' || $_GET['authors_separator'] == 'OR') $authors_array = explode(' ', $_GET['authors']);

		while ($authors = each($authors_array)) {

			$like_query = str_replace("\\", "\\\\", $authors[1]);
			$like_query = str_replace("%", "\%", $like_query);
			$like_query = str_replace("_", "\_", $like_query);
			$like_query = str_replace("<*>", "%", $like_query);
			$like_query = str_replace("<?>", "_", $like_query);

			$regexp_query = addcslashes($authors[1],"\044\050..\053\056\057\074\076\077\133\134\136\173\174");
			$regexp_query = str_replace('\<\*\>', '.*', $regexp_query);
			$regexp_query = str_replace('\<\?\>', '.?', $regexp_query);

			$like_query = $dbHandle->quote("%$like_query%");
			$regexp_query = str_replace("'", "''", $regexp_query);

			$translation = utf8_deaccent($authors[1]);

			if ($translation != $authors[1]) {

				$like_query_translated = $dbHandle->quote("%$translation%");
				$regexp_query_translated = str_replace("'", "''", $translation);

				$like_sql = "authors LIKE $like_query ESCAPE '\' OR authors_ascii LIKE $like_query_translated ESCAPE '\'";
				$regexp_sql = "regexp_match(authors, '$regexp_query', $case2) OR regexp_match(authors_ascii, '$regexp_query_translated', $case2)";

			} else {

				$like_sql = "authors_ascii LIKE $like_query ESCAPE '\'";
				$regexp_sql = "regexp_match(authors_ascii, '$regexp_query', $case2)";

			}

			if ($whole_words == 1) {
				$authors_regexp[] = '('.$like_sql.') AND ('.$regexp_sql.')';
			} else {
				$authors_regexp[] = '('.$like_sql.')';
			}
		}

		if ($_GET['authors_separator'] == 'AND') $search_string[] = join (' AND ', $authors_regexp);
		if ($_GET['authors_separator'] == 'OR') $search_string[] = join (' OR ', $authors_regexp);
		if ($_GET['authors_separator'] == 'PHRASE') $search_string[] =  join ('', $authors_regexp);
	}

	#######################################################################

	if (!empty($_GET['journal']) && $_GET['searchtype'] == 'metadata') {

		$journal_array = array ($_GET['journal']);
		if ($_GET['journal_separator'] == 'AND' || $_GET['journal_separator'] == 'OR') $journal_array = explode(' ', $_GET['journal']);

		while ($journal = each($journal_array)) {

			$like_query = str_replace("\\", "\\\\", $journal[1]);
			$like_query = str_replace("%", "\%", $like_query);
			$like_query = str_replace("_", "\_", $like_query);
			$like_query = str_replace("<*>", "%", $like_query);
			$like_query = str_replace("<?>", "_", $like_query);

			$regexp_query = addcslashes($journal[1],"\044\050..\053\056\057\074\076\077\133\134\136\173\174");
			$regexp_query = str_replace('\<\*\>', '.*', $regexp_query);
			$regexp_query = str_replace('\<\?\>', '.?', $regexp_query);

			$like_query = $dbHandle->quote("%$like_query%");
			$regexp_query = str_replace("'", "''", $regexp_query);

			$translation = utf8_deaccent($journal[1]);

			if ($translation != $journal[1]) {

				$like_query_translated = $dbHandle->quote("%$translation%");
				$regexp_query_translated = str_replace("'", "''", $translation);

				$like_sql = "journal LIKE $like_query ESCAPE '\' OR journal LIKE $like_query_translated ESCAPE '\'";
				$regexp_sql = "regexp_match(journal, '$regexp_query', $case2) OR regexp_match(journal, '$regexp_query_translated', $case2)";

			} else {

				$like_sql = "journal LIKE $like_query ESCAPE '\'";
				$regexp_sql = "regexp_match(journal, '$regexp_query', $case2)";

			}

			if ($whole_words == 1) {
				$journal_regexp[] = '('.$like_sql.') AND ('.$regexp_sql.')';
			} else {
				$journal_regexp[] = '('.$like_sql.')';
			}
    		}

		if ($_GET['journal_separator'] == 'AND') $search_string[] = join (' AND ', $journal_regexp);
		if ($_GET['journal_separator'] == 'OR') $search_string[] = join (' OR ', $journal_regexp);
		if ($_GET['journal_separator'] == 'PHRASE') $search_string[] =  join ('', $journal_regexp);
	}

	#######################################################################

	if (!empty($_GET['secondary_title']) && $_GET['searchtype'] == 'metadata') {

		$secondary_title_array = array ($_GET['secondary_title']);
		if ($_GET['secondary_title_separator'] == 'AND' || $_GET['secondary_title_separator'] == 'OR') $secondary_title_array = explode(' ', $_GET['secondary_title']);

		while ($secondary_title = each($secondary_title_array)) {

			$like_query = str_replace("\\", "\\\\", $secondary_title[1]);
			$like_query = str_replace("%", "\%", $like_query);
			$like_query = str_replace("_", "\_", $like_query);
			$like_query = str_replace("<*>", "%", $like_query);
			$like_query = str_replace("<?>", "_", $like_query);

			$regexp_query = addcslashes($secondary_title[1],"\044\050..\053\056\057\074\076\077\133\134\136\173\174");
			$regexp_query = str_replace('\<\*\>', '.*', $regexp_query);
			$regexp_query = str_replace('\<\?\>', '.?', $regexp_query);

			$like_query = $dbHandle->quote("%$like_query%");
			$regexp_query = str_replace("'", "''", $regexp_query);

			$translation = utf8_deaccent($secondary_title[1]);

			if ($translation != $secondary_title[1]) {

				$like_query_translated = $dbHandle->quote("%$translation%");
				$regexp_query_translated = str_replace("'", "''", $translation);

				$like_sql = "secondary_title LIKE $like_query ESCAPE '\' OR secondary_title LIKE $like_query_translated ESCAPE '\'";
				$regexp_sql = "regexp_match(secondary_title, '$regexp_query', $case2) OR regexp_match(secondary_title, '$regexp_query_translated', $case2)";

			} else {

				$like_sql = "secondary_title LIKE $like_query ESCAPE '\'";
				$regexp_sql = "regexp_match(secondary_title, '$regexp_query', $case2)";

			}

			if ($whole_words == 1) {
				$secondary_title_regexp[] = '('.$like_sql.') AND ('.$regexp_sql.')';
			} else {
				$secondary_title_regexp[] = '('.$like_sql.')';
			}
    		}

		if ($_GET['secondary_title_separator'] == 'AND') $search_string[] = join (' AND ', $secondary_title_regexp);
		if ($_GET['secondary_title_separator'] == 'OR') $search_string[] = join (' OR ', $secondary_title_regexp);
		if ($_GET['secondary_title_separator'] == 'PHRASE') $search_string[] =  join ('', $secondary_title_regexp);
	}

	#######################################################################

	if (!empty($_GET['affiliation']) && $_GET['searchtype'] == 'metadata') {

		$affiliation_array = array ($_GET['affiliation']);
		if ($_GET['affiliation_separator'] == 'AND' || $_GET['affiliation_separator'] == 'OR') $affiliation_array = explode(' ', $_GET['affiliation']);

		while ($affiliation = each($affiliation_array)) {

			$like_query = str_replace("\\", "\\\\", $affiliation[1]);
			$like_query = str_replace("%", "\%", $like_query);
			$like_query = str_replace("_", "\_", $like_query);
			$like_query = str_replace("<*>", "%", $like_query);
			$like_query = str_replace("<?>", "_", $like_query);

			$regexp_query = addcslashes($affiliation[1],"\044\050..\053\056\057\074\076\077\133\134\136\173\174");
			$regexp_query = str_replace('\<\*\>', '.*', $regexp_query);
			$regexp_query = str_replace('\<\?\>', '.?', $regexp_query);

			$like_query = $dbHandle->quote("%$like_query%");
			$regexp_query = str_replace("'", "''", $regexp_query);

			$translation = utf8_deaccent($affiliation[1]);

			if ($translation != $affiliation[1]) {

				$like_query_translated = $dbHandle->quote("%$translation%");
				$regexp_query_translated = str_replace("'", "''", $translation);

				$like_sql = "affiliation LIKE $like_query ESCAPE '\' OR affiliation LIKE $like_query_translated ESCAPE '\'";
				$regexp_sql = "regexp_match(affiliation, '$regexp_query', $case2) OR regexp_match(affiliation, '$regexp_query_translated', $case2)";

			} else {

				$like_sql = "affiliation LIKE $like_query ESCAPE '\'";
				$regexp_sql = "regexp_match(affiliation, '$regexp_query', $case2)";

			}

			if ($whole_words == 1) {
				$affiliation_regexp[] = '('.$like_sql.') AND ('.$regexp_sql.')';
			} else {
				$affiliation_regexp[] = '('.$like_sql.')';
			}
    		}

		if ($_GET['affiliation_separator'] == 'AND') $search_string[] = join (' AND ', $affiliation_regexp);
		if ($_GET['affiliation_separator'] == 'OR') $search_string[] = join (' OR ', $affiliation_regexp);
		if ($_GET['affiliation_separator'] == 'PHRASE') $search_string[] =  join ('', $affiliation_regexp);
	}

	#######################################################################

	if (!empty($_GET['title']) && $_GET['searchtype'] == 'metadata') {

		$title_array = array ($_GET['title']);
		if ($_GET['title_separator'] == 'AND' || $_GET['title_separator'] == 'OR') $title_array = explode(' ', $_GET['title']);

		while ($title = each($title_array)) {

			$like_query = str_replace("\\", "\\\\", $title[1]);
			$like_query = str_replace("%", "\%", $like_query);
			$like_query = str_replace("_", "\_", $like_query);
			$like_query = str_replace("<*>", "%", $like_query);
			$like_query = str_replace("<?>", "_", $like_query);

			$regexp_query = addcslashes($title[1],"\044\050..\053\056\057\074\076\077\133\134\136\173\174");
			$regexp_query = str_replace('\<\*\>', '.*', $regexp_query);
			$regexp_query = str_replace('\<\?\>', '.?', $regexp_query);

			$like_query = $dbHandle->quote("%$like_query%");
			$regexp_query = str_replace("'", "''", $regexp_query);

			$translation = utf8_deaccent($title[1]);

			if ($translation != $title[1]) {

				$like_query_translated = $dbHandle->quote("%$translation%");
				$regexp_query_translated = str_replace("'", "''", $translation);

				$like_sql = "title LIKE $like_query ESCAPE '\' OR title_ascii LIKE $like_query_translated ESCAPE '\'";
				$regexp_sql = "regexp_match(title, '$regexp_query', $case2) OR regexp_match(title_ascii, '$regexp_query_translated', $case2)";

			} else {

				$like_sql = "title_ascii LIKE $like_query ESCAPE '\'";
				$regexp_sql = "regexp_match(title_ascii, '$regexp_query', $case2)";

			}

			if ($whole_words == 1) {
				$title_regexp[] = '('.$like_sql.') AND ('.$regexp_sql.')';
			} else {
				$title_regexp[] = '('.$like_sql.')';
			}
		}

		if ($_GET['title_separator'] == 'AND') $search_string[] = join (' AND ', $title_regexp);
		if ($_GET['title_separator'] == 'OR') $search_string[] = join (' OR ', $title_regexp);
		if ($_GET['title_separator'] == 'PHRASE') $search_string[] =  join ('', $title_regexp);
	}


	#######################################################################

	if (!empty($_GET['keywords']) && $_GET['searchtype'] == 'metadata') {

		$keywords_array = array ($_GET['keywords']);
		if ($_GET['keywords_separator'] == 'AND' || $_GET['keywords_separator'] == 'OR') $keywords_array = explode(' ', $_GET['keywords']);

		while ($keywords = each($keywords_array)) {

			$like_query = str_replace("\\", "\\\\", $keywords[1]);
			$like_query = str_replace("%", "\%", $like_query);
			$like_query = str_replace("_", "\_", $like_query);
			$like_query = str_replace("<*>", "%", $like_query);
			$like_query = str_replace("<?>", "_", $like_query);

			$regexp_query = addcslashes($keywords[1],"\044\050..\053\056\057\074\076\077\133\134\136\173\174");
			$regexp_query = str_replace('\<\*\>', '.*', $regexp_query);
			$regexp_query = str_replace('\<\?\>', '.?', $regexp_query);

			$like_query = $dbHandle->quote("%$like_query%");
			$regexp_query = str_replace("'", "''", $regexp_query);

			$translation = utf8_deaccent($keywords[1]);

			if ($translation != $keywords[1]) {

				$like_query_translated = $dbHandle->quote("%$translation%");
				$regexp_query_translated = str_replace("'", "''", $translation);

				$like_sql = "keywords LIKE $like_query ESCAPE '\' OR keywords LIKE $like_query_translated ESCAPE '\'";
				$regexp_sql = "regexp_match(keywords, '$regexp_query', $case2) OR regexp_match(keywords, '$regexp_query_translated', $case2)";

			} else {

				$like_sql = "keywords LIKE $like_query ESCAPE '\'";
				$regexp_sql = "regexp_match(keywords, '$regexp_query', $case2)";

			}

			if ($whole_words == 1) {
				$keywords_regexp[] = '('.$like_sql.') AND ('.$regexp_sql.')';
			} else {
				$keywords_regexp[] = '('.$like_sql.')';
			}
		}

		if ($_GET['keywords_separator'] == 'AND') $search_string[] = join (' AND ', $keywords_regexp);
		if ($_GET['keywords_separator'] == 'OR') $search_string[] = join (' OR ', $keywords_regexp);
		if ($_GET['keywords_separator'] == 'PHRASE') $search_string[] =  join ('', $keywords_regexp);
	}


	#######################################################################

	if (!empty($_GET['abstract']) && $_GET['searchtype'] == 'metadata') {

		$abstract_array = array ($_GET['abstract']);
		if ($_GET['abstract_separator'] == 'AND' || $_GET['abstract_separator'] == 'OR') $abstract_array = explode(' ', $_GET['abstract']);

		while ($abstract = each($abstract_array)) {

			$like_query = str_replace("\\", "\\\\", $abstract[1]);
			$like_query = str_replace("%", "\%", $like_query);
			$like_query = str_replace("_", "\_", $like_query);
			$like_query = str_replace("<*>", "%", $like_query);
			$like_query = str_replace("<?>", "_", $like_query);

			$regexp_query = addcslashes($abstract[1],"\044\050..\053\056\057\074\076\077\133\134\136\173\174");
			$regexp_query = str_replace('\<\*\>', '.*', $regexp_query);
			$regexp_query = str_replace('\<\?\>', '.?', $regexp_query);

			$like_query = $dbHandle->quote("%$like_query%");
			$regexp_query = str_replace("'", "''", $regexp_query);

			$translation = utf8_deaccent($abstract[1]);

			if ($translation != $abstract[1]) {

				$like_query_translated = $dbHandle->quote("%$translation%");
				$regexp_query_translated = str_replace("'", "''", $translation);

				$like_sql = "title LIKE $like_query ESCAPE '\' OR abstract LIKE $like_query ESCAPE '\' OR
						title_ascii LIKE $like_query_translated ESCAPE '\' OR abstract_ascii LIKE $like_query_translated ESCAPE '\'";
				$regexp_sql = "regexp_match(title, '$regexp_query', $case2) OR regexp_match(abstract, '$regexp_query', $case2) OR
						regexp_match(title_ascii, '$regexp_query_translated', $case2) OR regexp_match(abstract_ascii, '$regexp_query_translated', $case2)";

			} else {

				$like_sql = "title_ascii LIKE $like_query ESCAPE '\' OR abstract_ascii LIKE $like_query ESCAPE '\'";
				$regexp_sql = "regexp_match(title_ascii, '$regexp_query', $case2) OR regexp_match(abstract_ascii, '$regexp_query', $case2)";

			}

			if ($whole_words == 1) {
				$abstract_regexp[] = '('.$like_sql.') AND ('.$regexp_sql.')';
			} else {
				$abstract_regexp[] = '('.$like_sql.')';
			}
		}

		if ($_GET['abstract_separator'] == 'AND') $search_string[] = join (' AND ', $abstract_regexp);
		if ($_GET['abstract_separator'] == 'OR') $search_string[] = join (' OR ', $abstract_regexp);
		if ($_GET['abstract_separator'] == 'PHRASE') $search_string[] =  join ('', $abstract_regexp);
	}

	#######################################################################

	if (!empty($_GET['year']) && $_GET['searchtype'] == 'metadata') {

		$year_array = explode(' ', $_GET['year']);

		while ($year = each($year_array)) {
			$year_regexp[] = "year=".intval($year[1]);
		}

		$search_string[] = join (' OR ', $year_regexp);
	}

	#######################################################################

	if (!empty($_GET['search_id']) && $_GET['searchtype'] == 'metadata') {

		$search_id_array = explode(' ', $_GET['search_id']);

		while ($search_id = each($search_id_array)) {
			$search_id_regexp[] = "id=".intval($search_id[1]);
		}

		$search_string[] = join (' OR ', $search_id_regexp);
	}

	#######################################################################

	if (!empty($search_string)) {

		if (count($search_string) > 1) {
			$search_string = join (') AND (', $search_string);
		} elseif (count($search_string) == 1) {
			$search_string = join ('', $search_string);
		}
		$search_string = '('.$search_string.')';

		$result_array = array();

		if (isset($_SESSION['searches'][$md5_query]['result']) && $_SESSION['searches'][$md5_query]['query_time'] >= filemtime($database_path.'library.sq3')) {

			$result_array = $_SESSION['searches'][$md5_query]['result'];
			$rows = count($result_array);

		} else {

			database_connect($database_path, 'library');

			$dbHandle->sqliteCreateFunction('regexp_match', 'sqlite_regexp', 3);
			if ($case == 1) $dbHandle->exec("PRAGMA case_sensitive_like = 1");

			$result = $dbHandle->query("SELECT id FROM library WHERE $rating_search $category_search $in $search_string ORDER BY $orderby COLLATE NOCASE $ordering");

			$dbHandle = null;

			$result_array = $result->fetchAll(PDO::FETCH_COLUMN);
			$rows = count($result_array);

			if ($_GET['select'] != 'clipboard') {

				$_SESSION['searches'][$md5_query]['result'] = $result_array;
				$_SESSION['searches'][$md5_query]['query_time'] = time();
			}
		}
	}

        ##########################notes#####################################

        if (!empty($_GET['notes']) && $_GET['searchtype'] == 'notes') {

                $notes_array = array ($_GET['notes']);
		if ($_GET['notes_separator'] == 'AND' || $_GET['notes_separator'] == 'OR') $notes_array = explode(' ', $_GET['notes']);


		while ($notes = each($notes_array)) {

			$like_query = str_replace("\\", "\\\\", $notes[1]);
			$like_query = str_replace("%", "\%", $like_query);
			$like_query = str_replace("_", "\_", $like_query);
			$like_query = str_replace("<*>", "%", $like_query);
			$like_query = str_replace("<?>", "_", $like_query);

			$regexp_query = addcslashes($notes[1],"\044\050..\053\056\057\074\076\077\133\134\136\173\174");
			$regexp_query = str_replace('\<\*\>', '.*', $regexp_query);
			$regexp_query = str_replace('\<\?\>', '.?', $regexp_query);

			$like_query = $dbHandle->quote("%$like_query%");
			$regexp_query = str_replace("'", "''", $regexp_query);

			$like_sql = "search_strip_tags(notes) LIKE $like_query ESCAPE '\'";
			$regexp_sql = "regexp_match(search_strip_tags(notes), '$regexp_query', $case2)";

			if ($whole_words == 1) {
				$notes_regexp[] = '('.$like_sql.') AND ('.$regexp_sql.')';
			} else {
				$notes_regexp[] = '('.$like_sql.')';
			}
		}

                if ($_GET['notes_separator'] == 'AND') $search_string = join (' AND ', $notes_regexp);
		if ($_GET['notes_separator'] == 'OR') $search_string = join (' OR ', $notes_regexp);
		if ($_GET['notes_separator'] == 'PHRASE') $search_string =  join ('', $notes_regexp);

		$result_array = array();

                if (isset($_SESSION['searches'][$md5_query]['result']) && $_SESSION['searches'][$md5_query]['query_time'] >= filemtime($database_path.'library.sq3')) {

			$result_array = $_SESSION['searches'][$md5_query]['result'];
			$rows = count($result_array);

		} else {

			$dbHandle = null;

			$notes_in = str_replace ("id IN", "fileID IN", $in);
			$notes_category_search = str_replace ("id IN", "fileID IN", $category_search);

			database_connect($database_path, 'library');

			$dbHandle->sqliteCreateFunction('search_strip_tags', 'sqlite_strip_tags', 1);
			$dbHandle->sqliteCreateFunction('regexp_match', 'sqlite_regexp', 3);
			if ($case == 1) $dbHandle->exec("PRAGMA case_sensitive_like = 1");

			$result = $dbHandle->query("SELECT fileID FROM notes
                                WHERE userID=".intval($_SESSION['user_id'])." AND $notes_category_search $notes_in $search_string");

			$result_ids = $result->fetchAll(PDO::FETCH_COLUMN);
			$result = null;

			$rows = count($result_ids);
			$result_string = join (",", $result_ids);
			$result_string = "id IN ($result_string)";

			$result = $dbHandle->query("SELECT id FROM library WHERE $result_string ORDER BY $orderby COLLATE NOCASE $ordering");
			$result_array = $result->fetchAll(PDO::FETCH_COLUMN);
			$result = null;
			$dbHandle = null;

			if ($_GET['select'] != 'clipboard') {
				$_SESSION['searches'][$md5_query]['result'] = $result_array;
				$_SESSION['searches'][$md5_query]['query_time'] = time();
			}
		}
        }

	##########################fulltext#####################################

	if (!empty($_GET['fulltext']) && $_GET['searchtype'] == 'pdf') {

		$stopwords = "a's, able, about, above, according, accordingly, across, actually, after, afterwards, again, against, ain't, all, allow, allows, almost, alone, along, already, also, although, always, am, among, amongst, an, and, another, any, anybody, anyhow, anyone, anything, anyway, anyways, anywhere, apart, appear, appreciate, appropriate, are, aren't, around, as, aside, ask, asking, associated, at, available, away, awfully, be, became, because, become, becomes, becoming, been, before, beforehand, behind, being, believe, below, beside, besides, best, better, between, beyond, both, brief, but, by, c'mon, c's, came, can, can't, cannot, cant, cause, causes, certain, certainly, changes, clearly, co, com, come, comes, concerning, consequently, consider, considering, contain, containing, contains, corresponding, could, couldn't, course, currently, definitely, described, despite, did, didn't, different, do, does, doesn't, doing, don't, done, down, downwards, during, each, edu, eg, eight, either, else, elsewhere, enough, entirely, especially, et, etc, even, ever, every, everybody, everyone, everything, everywhere, ex, exactly, example, except, far, few, fifth, first, five, followed, following, follows, for, former, formerly, forth, four, from, further, furthermore, get, gets, getting, given, gives, go, goes, going, gone, got, gotten, greetings, had, hadn't, happens, hardly, has, hasn't, have, haven't, having, he, he's, hello, help, hence, her, here, here's, hereafter, hereby, herein, hereupon, hers, herself, hi, him, himself, his, hither, hopefully, how, howbeit, however, i'd, i'll, i'm, i've, ie, if, ignored, immediate, in, inasmuch, inc, indeed, indicate, indicated, indicates, inner, insofar, instead, into, inward, is, isn't, it, it'd, it'll, it's, its, itself, just, keep, keeps, kept, know, knows, known, last, lately, later, latter, latterly, least, less, lest, let, let's, like, liked, likely, little, look, looking, looks, ltd, mainly, many, may, maybe, me, mean, meanwhile, merely, might, more, moreover, most, mostly, much, must, my, myself, name, namely, nd, near, nearly, necessary, need, needs, neither, never, nevertheless, new, next, nine, no, nobody, non, none, noone, nor, normally, not, nothing, novel, now, nowhere, obviously, of, off, often, oh, ok, okay, old, on, once, one, ones, only, onto, or, other, others, otherwise, ought, our, ours, ourselves, out, outside, over, overall, own, particular, particularly, per, perhaps, placed, please, plus, possible, presumably, probably, provides, que, quite, qv, rather, rd, re, really, reasonably, regarding, regardless, regards, relatively, respectively, right, said, same, saw, say, saying, says, second, secondly, see, seeing, seem, seemed, seeming, seems, seen, self, selves, sensible, sent, serious, seriously, seven, several, shall, she, should, shouldn't, since, six, so, some, somebody, somehow, someone, something, sometime, sometimes, somewhat, somewhere, soon, sorry, specified, specify, specifying, still, sub, such, sup, sure, t's, take, taken, tell, tends, th, than, thank, thanks, thanx, that, that's, thats, the, their, theirs, them, themselves, then, thence, there, there's, thereafter, thereby, therefore, therein, theres, thereupon, these, they, they'd, they'll, they're, they've, think, third, this, thorough, thoroughly, those, though, three, through, throughout, thru, thus, to, together, too, took, toward, towards, tried, tries, truly, try, trying, twice, two, un, under, 				unfortunately, unless, unlikely, until, unto, up, upon, us, use, used, useful, uses, using, usually, value, various, very, via, viz, vs, want, wants, was, wasn't, way, we, we'd, we'll, we're, we've, welcome, well, went, were, weren't, what, what's, whatever, when, whence, whenever, where, where's, whereafter, whereas, whereby, wherein, whereupon, wherever, whether, which, while, whither, who, who's, whoever, whole, whom, whose, why, will, willing, wish, with, within, without, won't, wonder, would, would, wouldn't, yes, yet, you, you'd, you'll, you're, you've, your, yours, yourself, yourselves, zero";

		$stopwords = explode (', ', $stopwords);

		$patterns = join("\b/ui /\b", $stopwords);
		$patterns = "/\b$patterns\b/ui";
		$patterns = explode(" ", $patterns);

		$_GET['fulltext'] = preg_replace ($patterns, '<*>', $_GET['fulltext']);

		$fulltext_array = explode(' ', $_GET['fulltext']);

		while ($fulltext = each($fulltext_array)) {

			$like_query = str_replace("\\", "\\\\", $fulltext[1]);
			$like_query = str_replace("%", "\%", $like_query);
			$like_query = str_replace("_", "\_", $like_query);
			$like_query = str_replace("<*>", "%", $like_query);
			$like_query = str_replace("<?>", "_", $like_query);

			$regexp_query = addcslashes($fulltext[1],"\044\050..\053\056\057\074\076\077\133\134\136\173\174");
			$regexp_query = str_replace('\<\*\>', '.*', $regexp_query);
			$regexp_query = str_replace('\<\?\>', '.?', $regexp_query);

			$like_query = $dbHandle->quote("%$like_query%");
			$regexp_query = str_replace("'", "''", $regexp_query);

			$translation = utf8_deaccent($fulltext[1]);

			if ($translation != $fulltext[1]) {

				$like_query_translated = $dbHandle->quote("%$translation%");
				$regexp_query_translated = str_replace("'", "''", $translation);

				$like_sql = "full_text LIKE $like_query ESCAPE '\' OR full_text LIKE $like_query_translated ESCAPE '\'";
				$regexp_sql = "regexp_match(full_text, '$regexp_query', $case2) OR regexp_match(full_text, '$regexp_query_translated', $case2)";

			} else {

				$like_sql = "full_text LIKE $like_query ESCAPE '\'";
				$regexp_sql = "regexp_match(full_text, '$regexp_query', $case2)";

			}

			if ($whole_words == 1) {
				$fulltext_regexp[] = '('.$like_sql.') AND ('.$regexp_sql.')';
			} else {
				$fulltext_regexp[] = '('.$like_sql.')';
			}
    		}

		if ($_GET['fulltext_separator'] == 'AND') $search_string = join (' AND ', $fulltext_regexp);
		if ($_GET['fulltext_separator'] == 'OR') $search_string = join (' OR ', $fulltext_regexp);

		$result_array = array();

		if (isset($_SESSION['searches'][$md5_query]['result']) && $_SESSION['searches'][$md5_query]['query_time'] >= filemtime($database_path.'fulltext.sq3')) {

			$result_array = $_SESSION['searches'][$md5_query]['result'];
			$rows = count($result_array);

		} else {

			$dbHandle = null;

			$fulltext_in = str_replace ("id IN", "fileID IN", $in);
			$fulltext_category_search = str_replace ("id IN", "fileID IN", $category_search);

			database_connect($database_path, 'fulltext');

			$dbHandle->sqliteCreateFunction('regexp_match', 'sqlite_regexp', 3);

			if ($case == 1) $dbHandle->exec("PRAGMA case_sensitive_like = 1");

			$result = $dbHandle->query("SELECT fileID FROM full_text WHERE $fulltext_category_search $fulltext_in $search_string");

			$result_ids = $result->fetchAll(PDO::FETCH_COLUMN);
			$result = null;
			$dbHandle = null;

			$rows = count($result_ids);
			$result_string = join (",", $result_ids);
			$result_string = "id IN ($result_string)";

			database_connect($database_path, 'library');
			$result = $dbHandle->query("SELECT id FROM library WHERE $result_string ORDER BY $orderby COLLATE NOCASE $ordering");
			$result_array = $result->fetchAll(PDO::FETCH_COLUMN);
			$result = null;
			$dbHandle = null;


			if ($_GET['select'] != 'clipboard') {

				$_SESSION['searches'][$md5_query]['result'] = $result_array;
				$_SESSION['searches'][$md5_query]['query_time'] = time();
			}
		}
	}

	#######################################################################

	if (!empty($result_array)) {

		$_SESSION['export_files'] = $result_array;
		$_SESSION['export_files_timestamp'] = time();
	
		$limited_result = array_slice($result_array, $from, $limit);
		$result_string = join (",", $limited_result);
		$result_string = "id IN ($result_string)";

		database_connect($database_path, 'library');
		$result = $dbHandle->query("SELECT id,file,authors,title,journal,secondary_title,year,volume,pages,abstract,uid,doi,url,addition_date,rating FROM library WHERE $result_string ORDER BY $orderby COLLATE NOCASE $ordering");
		$result = $result->fetchAll(PDO::FETCH_ASSOC);
		$dbHandle = null;
	}

	$microtime2 = microtime(true);
	$microtime = $microtime2 - $microtime1;
	$microtime = sprintf ("%01.2f sec", $microtime);

	if ($rows > 0) {

		print '<div id="display-content">';
?>
<table cellspacing="1" id="customization" style="border-spacing:2px 0px;cursor:pointer">
 <tr>
  <td class="ui-state-highlight" id="displaybutton">&nbsp;Display&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $display == 'brief' ? 'off' : 'on'; ?>" style="float:left"></span>Title&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $display == 'summary' ? 'off' : 'on'; ?>" style="float:left"></span>Summary&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $display == 'abstract' ? 'off' : 'on'; ?>" style="float:left"></span>Abstract&nbsp;</td>
  <td class="ui-state-highlight" id="orderbybutton">&nbsp;Order by&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $orderby == 'year' ? 'off' : 'on'; ?>" style="float:left"></span>Date Published&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $orderby == 'id' ? 'off' : 'on'; ?>" style="float:left"></span>Date Added&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $orderby == 'rating' ? 'off' : 'on'; ?>" style="float:left"></span>Rating&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $orderby == 'journal' ? 'off' : 'on'; ?>" style="float:left"></span>Journal&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $orderby == 'authors' ? 'off' : 'on'; ?>" style="float:left"></span>Authors&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $orderby == 'title' ? 'off' : 'on'; ?>" style="float:left"></span>Title&nbsp;</td>
  <td class="ui-state-highlight" id="showbutton">&nbsp;Show&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $limit == 5 ? 'off' : 'on'; ?>" style="float:left"></span>5&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $limit == 10 ? 'off' : 'on'; ?>" style="float:left"></span>10&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $limit == 15 ? 'off' : 'on'; ?>" style="float:left"></span>15&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $limit == 20 ? 'off' : 'on'; ?>" style="float:left"></span>20&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $limit == 50 ? 'off' : 'on'; ?>" style="float:left"></span>50&nbsp;</td>
  <td class="alternating_row"><span class="ui-icon ui-icon-radio-<?php print $limit == 100 ? 'off' : 'on'; ?>" style="float:left"></span>100&nbsp;</td>
 </tr>
</table>
<script type="text/javascript">
	$('#customization').data('redirection','<?php print preg_replace('/(from=\d*)(\&|$)/', 'from=0$2', basename($_SERVER['PHP_SELF']).'?'.$_SERVER['QUERY_STRING']); ?>')
		.find('span.ui-icon-radio-on').closest('td').find("td:not([id])").andSelf().hide();
</script>
<?php
	}

	$search_query_array = array_merge((array)$anywhere_array, (array)$authors_array, (array)$journal_array, (array)$secondary_title_array, (array)$affiliation_array, (array)$keywords_array, 
                            (array)$title_array, (array)$abstract_array, (array)$year_array, (array)$search_id_array, (array)$fulltext_array, (array)$notes_array);

	$search_query = join (' ', $search_query_array);

	$_SESSION['searches'][$md5_query]['query'] = $search_query;

	while ($term = each($search_query_array)) {

		if (!empty($term[1])) $search_query_array_translated[] = utf8_deaccent($term[1]);
	}
  
	$search_query_highlight_array = array_merge ((array)$search_query_array, (array)$search_query_array_translated);
	$search_query_highlight_array = array_unique (array_filter($search_query_highlight_array));

	if (isset($_GET['select']) && $_GET['select'] == 'shelf' && isset($_SESSION["auth"])) {
		$what = "Shelf";
        } elseif (isset($_GET['select']) && $_GET['select'] == 'desk') {
		$what = "Project: ".$project_name;
	} elseif (isset($_GET['select']) && $_GET['select'] == 'clipboard') {
		$what = "Clipboard";
	} else {
		$what = "Library";
	}

	if (!empty($search_query)) print '<div id="list-title" style="font-weight: bold; padding: 2px">'.$what.' &raquo; Query: '.htmlspecialchars($search_query).'</div>';

	$url_array = array ();
	reset($_GET);
	while (list($name,$value) = each($_GET)) {
		if (is_array($_GET[$name])) {
			while (list(,$value2) = each($_GET[$name])) {
				if (!empty($value2)) $url_array[] = urlencode($name.'[]').'='.urlencode($value2);
			}
		} elseif ($name != 'from') {
			if (!empty($value)) $url_array[] = urlencode($name).'='.urlencode($value);
		}
	}
	$url_string = join ('&',$url_array);

	if ($rows > 0) {

		$items_from = $from + 1;
		(($from + $limit) > $rows) ? $items_to = $rows : $items_to = $from + $limit;

		print '<table cellspacing="0" class="top" style="margin-bottom:1px"><tr><td style="width: 21em">';

		print '<div class="ui-state-highlight ui-corner-top'.($from == 0 ? ' ui-state-disabled' : '').'" style="float:left;margin-left:2px;width:28px">'
			.($from == 0 ? '' : '<a href="'.htmlspecialchars("search.php?$url_string&from=0").'" class="navigation" style="display:block">').
			'<span class="ui-icon ui-icon-triangle-1-w" style="float:right;width:16px"></span>
			<span class="ui-icon ui-icon-triangle-1-w" style="float:left;width:10px;overflow:hidden"></span>'
			.($from == 0 ? '' : '</a>').
		      '</div>';

		print '<div class="ui-state-highlight ui-corner-top'.($from == 0 ? ' ui-state-disabled' : '').'" style="float:left;margin-left:2px;width:5.1em">'
		      .($from == 0 ? '' : '<a class="navigation" href="'.htmlspecialchars("search.php?$url_string&from=".($from-$limit)).'" style="color:black;display:block;width:100%">').
		      '<span class="ui-icon ui-icon-triangle-1-w" style="float:left"></span>Back&nbsp;'
		      .($from == 0 ? '' : '</a>').
		     '</div>';
		    
		if (isset($_SESSION['auth'])) print '<div id="exportbutton" class="ui-state-highlight ui-corner-top" style="float:left;margin-left:2px">
			 <span class="ui-icon ui-icon-suitcase" style="float:left"></span>Export&nbsp;
			</div>
			<div class="ui-state-highlight ui-corner-top" style="float:left;margin-left:2px" onclick="window.print()">
			 <span class="ui-icon ui-icon-print" style="float:left"></span>Print&nbsp;
			</div>';

		print '</td><td style="text-align: center">Items '.$items_from.'-'.$items_to.' of <span id="total-items">'.$rows.'</span> in '.$microtime.'.</td>';

		print '<td style="width: 22em">';

		(($rows % $limit) == 0) ? $lastpage = $rows - $limit - ($rows % $limit) : $lastpage = $rows - ($rows % $limit);

		print '<div class="ui-state-highlight ui-corner-top'.(($rows > ($from + $limit)) ? '' : ' ui-state-disabled').'" style="float:right;margin-right:2px;width:29px">'
			   .(($rows > ($from + $limit)) ? '<a class="navigation" href="'.htmlspecialchars("search.php?$url_string&from=$lastpage").'">' : '').
			   '<span class="ui-icon ui-icon-triangle-1-e" style="float:right;width:16px"></span>
			   <span class="ui-icon ui-icon-triangle-1-e" style="float:left;width:11px;overflow:hidden"></span>'
			   .(($rows > ($from + $limit)) ? '</a>' : '').
			'</div>';

		print '<div class="ui-state-highlight ui-corner-top'.(($rows > ($from + $limit)) ? '' : ' ui-state-disabled').'" style="width:5.1em;float:right;margin-right:2px">'
			  .(($rows > ($from + $limit)) ? '<a class="navigation" href="'.htmlspecialchars("search.php?$url_string&from=".($from+$limit)).'" style="color:black;display:block;width:100%">' : '').
			  '<span class="ui-icon ui-icon-triangle-1-e" style="float:right"></span>&nbsp;Next'
			  .(($rows > ($from + $limit)) ? '</a>' : '').
			'</div>';

		print '<div class="ui-state-highlight ui-corner-top" id="pgdown" style="float: right;width: 5em;margin-right:2px">PgDown</div>';

              if (isset($_SESSION['auth'])) print '<div id="omnitoolbutton" class="ui-state-highlight ui-corner-top" style="float:right;margin-right:2px">'
			  .'<span class="ui-icon ui-icon-wrench" style="float:left"></span>Omnitool&nbsp;</div>';

		print '</td></tr></table>';

		if (!isset($dbHandle)) database_connect($database_path, 'library');
		show_search_results($result, $_GET['select'], $display, $search_query_highlight_array, $shelf_files, $desktop_projects, $dbHandle);

		print '<table cellspacing="0" class="top" style="margin:1px 0px 2px 0px"><tr><td style="width:50%">';

		print '<div class="ui-state-highlight ui-corner-bottom'.($from == 0 ? ' ui-state-disabled' : '').'" style="float:left;margin-left:2px;width:28px">'
			.($from == 0 ? '' : '<a href="'.htmlspecialchars("search.php?$url_string&from=0").'" class="navigation" style="display:block">').
			'<span class="ui-icon ui-icon-triangle-1-w" style="float:right;width:16px"></span>
			<span class="ui-icon ui-icon-triangle-1-w" style="float:left;width:10px;overflow:hidden"></span>'
			.($from == 0 ? '' : '</a>').
		      '</div>';

		print '<div class="ui-state-highlight ui-corner-bottom'.($from == 0 ? ' ui-state-disabled' : '').'" style="float:left;margin-left:2px;width:5.1em">'
		      .($from == 0 ? '' : '<a class="navigation" href="'.htmlspecialchars("search.php?$url_string&from=".($from-$limit)).'" style="color:black;display:block;width:100%">').
		      '<span class="ui-icon ui-icon-triangle-1-w" style="float:left"></span>Back&nbsp;'
		      .($from == 0 ? '' : '</a>').
		     '</div>';

		print '</td><td style="width:50%">';

		print '<div class="ui-state-highlight ui-corner-bottom'.(($rows > ($from + $limit)) ? '' : ' ui-state-disabled').'" style="float:right;margin-right:2px;width:29px">'
			   .(($rows > ($from + $limit)) ? '<a class="navigation" href="'.htmlspecialchars("search.php?$url_string&from=$lastpage").'">' : '').
			   '<span class="ui-icon ui-icon-triangle-1-e" style="float:right;width:16px"></span>
			   <span class="ui-icon ui-icon-triangle-1-e" style="float:left;width:11px;overflow:hidden"></span>'
			   .(($rows > ($from + $limit)) ? '</a>' : '').
			'</div>';

		print '<div class="ui-state-highlight ui-corner-bottom'.(($rows > ($from + $limit)) ? '' : ' ui-state-disabled').'" style="width:5.1em;float:right;margin-right:2px">'
			  .(($rows > ($from + $limit)) ? '<a class="navigation" href="'.htmlspecialchars("search.php?$url_string&from=".($from+$limit)).'" style="color:black;display:block;width:100%">' : '').
			  '<span class="ui-icon ui-icon-triangle-1-e" style="float:right"></span>&nbsp;Next'
			  .(($rows > ($from + $limit)) ? '</a>' : '').
			'</div>';

		print '<div class="ui-state-highlight ui-corner-bottom" id="pgup" style="float:right;width:5em;margin-right:2px">PgUp</div>';

		print "\n  </td>\n </tr>\n</table>";

	} else {
		print '<div style="position:relative;top:43%;left:43%;color:#bfbeb9;font-size:28px;width:200px"><b>No Hits</b></div>';
	}
    print '<div>';
    die();
}
?>
<div style="text-align:right">
<table style="margin-left:auto;margin-right:1px" id="advancedsearchtabs">
<tr>
<td>
     <table cellspacing=0 class="ui-state-highlight ui-corner-top" style="margin-left:2px" id="tab-search-ref">
     <tr>
      <td>
	   &nbsp;Search References&nbsp;
	  </td>
     </tr>
     </table>
</td>
<td>
     <table cellspacing=0 class="ui-state-highlight ui-corner-top" style="margin-left:2px" id="tab-search-pdf">
     <tr>
      <td>
	   &nbsp;Search PDFs&nbsp;
	  </td>
     </tr>
     </table>
</td>
<td style="<?php if(!isset($_SESSION['auth'])) print 'display:none'; ?>">
     <table cellspacing=0 class="ui-state-highlight ui-corner-top" style="margin-left:2px" id="tab-search-notes">
     <tr>
      <td>
	   &nbsp;Search Notes&nbsp;
	  </td>
     </tr>
     </table>
</td>
</tr>
</table>
<div class="search-div">
<form action="search.php" method="GET" class="advancedsearchform" id="search-metadata">
<input type="hidden" name="searchtype" value="metadata">
<table cellspacing=0 class="threed" style="width:680px;margin-left:auto;margin-right:0px">
<tr>
<td class="threed" style="width:9em">
Anywhere:
</td>
<td class="threed">
<?php search_row('anywhere'); ?>
</td></tr>
<tr>
<td class="threed">
Authors:
</td>
<td valign="top" class="threed">
<?php search_row('authors'); ?>
</td></tr>
<tr>
<td class="threed">
Title:
</td>
<td valign="top" class="threed">
<?php search_row('title'); ?>
</td></tr>
<tr>
<td class="threed">
Title/Abstract:
</td>
<td valign="top" class="threed">
<?php search_row('abstract'); ?>
</td></tr>
<tr>
<td class="threed">
Keywords:
</td>
<td valign="top" class="threed">
<?php search_row('keywords'); ?>
</td></tr>
<tr>
<td class="threed">
Journal:
</td>
<td class="threed">
<?php search_row('journal'); ?>
</td></tr>
<tr>
<td class="threed">
Secondary title:
</td>
<td class="threed">
<?php search_row('secondary_title'); ?>
</td></tr>
<tr>
<td class="threed">
Affiliation:
</td>
<td class="threed">
<?php search_row('affiliation'); ?>
</td></tr>
<tr>
<td class="threed">
Year:
</td>
<td class="threed">
<input type="text"  size="70" style="width:99.5%" name="year" value="<?php print isset($_SESSION['session_year']) ? htmlspecialchars($_SESSION['session_year']) : '';  ?>">
<table border=0 cellspacing=0 cellpadding=0>
 <tr>
  <td style="line-height:16px">
   <span class="ui-icon ui-icon-radio-off" style="float:left"></span>at least one of the words (OR)&nbsp;
  </td>
 </tr>
</table>
</td></tr>
<tr>
<td class="threed">
I, Librarian ID:
</td>
<td class="threed">
<input type="text" size="70" style="width:99.5%" name="search_id" value="<?php print isset($_SESSION['session_search_id']) ? htmlspecialchars($_SESSION['session_search_id']) : '';  ?>">
<table border=0 cellspacing=0>
 <tr>
  <td style="line-height:16px">
   <span class="ui-icon ui-icon-radio-off" style="float:left"></span>at least one of the words (OR)&nbsp;
  </td>
 </tr>
</table>
</td></tr>
<tr>
<td class="threed" style="width:9em">
Search in:
</td>
<td class="threed" style="text-align:left">
<select name="category">
<option value="all">all categories</option>
<option value="0">!unassigned</option>
<?php
	database_connect($database_path, 'library');

        if ($_GET['select'] == 'shelf' || $_GET['select'] == 'desk' || $_GET['select'] == 'clipboard') {
            $dbHandle->exec("PRAGMA temp_store = MEMORY");
            $dbHandle->exec("PRAGMA synchronous = OFF");
            $dbHandle->query("CREATE TEMPORARY TABLE subfiles (fileID INTEGER PRIMARY KEY)");
            $subfiles = "filescategories.fileID IN (SELECT fileID FROM subfiles)";
	}

	if ($_GET['select'] == 'shelf') {
            $dbHandle->query("INSERT INTO subfiles SELECT fileID FROM shelves WHERE userID=".intval($_SESSION['user_id'])."");
	}

        if ($_GET['select'] == 'desk' && is_numeric($_GET['project'])) {
            $dbHandle->query("INSERT INTO subfiles SELECT fileID FROM projectsfiles WHERE projectID=".intval($_GET['project'])."");
	}

	if ($_GET['select'] == 'clipboard' && !empty($_SESSION['session_clipboard'])) {
            $dbHandle->beginTransaction();
            foreach ($_SESSION['session_clipboard'] as $clipboard_file) {
                    $dbHandle->query("INSERT INTO subfiles VALUES (".intval($clipboard_file).")");
            }
            $dbHandle->commit();
	}
        if (!empty($subfiles)) $subfiles = "WHERE ".$subfiles;

        if ($_GET['select'] == 'library') {
                $result = $dbHandle->query("SELECT categoryID,category
                FROM categories
                ORDER BY category COLLATE NOCASE ASC");
        } elseif ($_GET['select'] == 'shelf' || $_GET['select'] == 'desk' || $_GET['select'] == 'clipboard') {
                $result = $dbHandle->query("SELECT DISTINCT categories.categoryID AS categoryID,category
                FROM filescategories
                INNER JOIN categories ON filescategories.categoryID=categories.categoryID
                $subfiles
                ORDER BY category COLLATE NOCASE ASC");
        }
       $category_array = $result->fetchAll(PDO::FETCH_ASSOC);
       $result = null;
	$dbHandle = null;

	foreach ($category_array as $category){

            print '<option value="'.htmlspecialchars($category['categoryID']).'"';
            if (isset($_SESSION['session_category']) && $_SESSION['session_category'] == $category['categoryID']) {
                    print ' selected';
            }
            print ">".htmlspecialchars($category['category'])."</option>\r\n";
	}

?>
</select>
</td></tr>
<tr>
<td class="threed">
Match:
</td>
<td class="threed">
<table border=0 cellspacing=0 cellpadding=0>
 <tr>
  <td class="select_span" style="line-height:16px">
   <input type="checkbox" name="whole_words" value="1" style="display:none" <?php if(isset($_SESSION['session_whole_words']) && $_SESSION['session_whole_words'] == 1) print ' checked'?>>
   <span class="ui-icon ui-icon-<?php print (isset($_SESSION['session_whole_words']) && $_SESSION['session_whole_words'] == 1) ? 'check' : 'close' ?>" style="float:left">
   </span>Whole words only&nbsp;
  </td>
  <td class="select_span" style="line-height:16px">
   <input type="checkbox" name="case" value="1" style="display:none" <?php print (isset($_SESSION['session_case']) && $_SESSION['session_case'] == 1) ? 'checked' : ''?>>
   <span class="ui-icon ui-icon-<?php print (isset($_SESSION['session_case']) && $_SESSION['session_case'] == 1) ? 'check' : 'close' ?>" style="float:left">
   </span>Match case&nbsp;
  </td>
 </tr>
</table>
</td></tr>
<tr>
<td class="threed">
Rating:
</td>
<td class="threed">
<table border=0 cellspacing=0 cellpadding=0>
 <tr>
  <td class="select_span" style="line-height:16px">
   <input type="checkbox" name="rating[]" value="1" style="display:none" <?php if(!isset($_SESSION['session_rating']) || (isset($_SESSION['session_rating']) && in_array(1, $_SESSION['session_rating']))) print ' checked'?>>
   <span class="ui-icon ui-icon-<?php print (!isset($_SESSION['session_rating']) || (isset($_SESSION['session_rating']) && in_array(1, $_SESSION['session_rating']))) ? 'check' : 'close' ?>" style="float:left">
   </span>Low&nbsp;
  </td>
  <td class="select_span" style="line-height:16px">
   <input type="checkbox" name="rating[]" value="2" style="display:none" <?php if(!isset($_SESSION['session_rating']) || (isset($_SESSION['session_rating']) && in_array(2, $_SESSION['session_rating']))) print ' checked'?>>
   <span class="ui-icon ui-icon-<?php print (!isset($_SESSION['session_rating']) || (isset($_SESSION['session_rating']) && in_array(2, $_SESSION['session_rating']))) ? 'check' : 'close' ?>" style="float:left">
   </span>Medium&nbsp;
  </td>
  <td class="select_span" style="line-height:16px">
   <input type="checkbox" name="rating[]" value="3" style="display:none" <?php if(!isset($_SESSION['session_rating']) || (isset($_SESSION['session_rating']) && in_array(3, $_SESSION['session_rating']))) print ' checked'?>>
   <span class="ui-icon ui-icon-<?php print (!isset($_SESSION['session_rating']) || (isset($_SESSION['session_rating']) && in_array(3, $_SESSION['session_rating']))) ? 'check' : 'close' ?>" style="float:left">
   </span>High&nbsp;
  </td>
 </tr>
</table>
</td></tr>
<?php
if (isset($_SESSION['auth'])) {
?>
<tr>
<td class="threed">
Save as:
</td>
<td class="threed">
<input type="text" name="searchname" style="width:99.5%">
</td></tr>
<?php
}
?>
<tr>
<td colspan="2">
<input type="submit" style="position:absolute;left:-999px;height:1px">
</td>
</tr>
</table>
</form>
</div>
<div class="search-div" style="display:none">
<form action="search.php" method="GET" class="advancedsearchform" id="search-pdfs">
<input type="hidden" name="searchtype" value="pdf">
<table cellspacing=0 class="threed" style="width:680px;margin-left:auto;margin-right:0px;border-top:0px solid #bfbeb9">
<tr>
<td class="threed" style="width:9em">
Full text:
</td>
<td class="threed">
<input type="text" size="70" style="width:99.5%" name="fulltext" value="<?php print isset($_SESSION['session_fulltext']) ? htmlspecialchars($_SESSION['session_fulltext']) : '';  ?>">
<table border=0 cellspacing=0 cellpadding=0>
 <tr>
  <td class="select_span" style="line-height:16px">
   <input type="radio" name="fulltext_separator" value="AND" style="display:none" <?php print (empty($_SESSION['session_fulltext_separator']) || (isset($_SESSION['session_fulltext_separator']) && $_SESSION['session_fulltext_separator'] == 'AND')) ? 'checked' : ''?>>
   <span class="ui-icon ui-icon-radio-<?php print (empty($_SESSION['session_fulltext_separator']) || (isset($_SESSION['session_fulltext_separator']) && $_SESSION['session_fulltext_separator'] == 'AND')) ? 'off' : 'on'?>" style="float:left">
   </span>all of the words (AND)&nbsp;
  </td>
  <td class="select_span" style="line-height:16px">
   <input type="radio" name="fulltext_separator" value="OR" style="display:none" <?php print (isset($_SESSION['session_fulltext_separator']) && $_SESSION['session_fulltext_separator'] == 'OR') ? 'checked' : ''?>>
   <span class="ui-icon ui-icon-radio-<?php print (isset($_SESSION['session_fulltext_separator']) && $_SESSION['session_fulltext_separator'] == 'OR') ? 'off' : 'on'?>" style="float:left">
   </span>at least one of the words (OR)&nbsp;
  </td>
 </tr>
</table>
</td></tr>
<tr>
<td class="threed" style="width:9em">
Search in:
</td>
<td class="threed" style="text-align:left">
<select name="category">
<option value="all">all categories</option>
<option value="0">!unassigned</option>
<?php
	foreach ($category_array as $category){

            print '<option value="'.htmlspecialchars($category['categoryID']).'"';
            if (isset($_SESSION['session_category']) && $_SESSION['session_category'] == $category['categoryID']) {
                    print ' selected';
            }
            print ">".htmlspecialchars($category['category'])."</option>\r\n";
	}
?>
</select>
</td></tr>
<tr>
<td class="threed">
Match:
</td>
<td class="threed">
<table border=0 cellspacing=0 cellpadding=0>
 <tr>
  <td class="select_span" style="line-height:16px">
   <input type="checkbox" name="whole_words" value="1" style="display:none" <?php if(isset($_SESSION['session_whole_words']) && $_SESSION['session_whole_words'] == 1) print ' checked'?>>
   <span class="ui-icon ui-icon-<?php print (isset($_SESSION['session_whole_words']) && $_SESSION['session_whole_words'] == 1) ? 'check' : 'close' ?>" style="float:left">
   </span>Whole words only&nbsp;
  </td>
  <td class="select_span" style="line-height:16px">
   <input type="checkbox" name="case" value="1" style="display:none" <?php print (isset($_SESSION['session_case']) && $_SESSION['session_case'] == 1) ? 'checked' : ''?>>
   <span class="ui-icon ui-icon-<?php print (isset($_SESSION['session_case']) && $_SESSION['session_case'] == 1) ? 'check' : 'close' ?>" style="float:left">
   </span>Match case&nbsp;
  </td>
 </tr>
</table>
</td></tr>
<?php
if (isset($_SESSION['auth'])) {
?>
<tr>
<td class="threed">
Save as:
</td>
<td class="threed">
<input type="text" name="searchname" style="width:99.5%">
</td></tr>
<?php
}
?>
<tr>
<td colspan="2">
<input type="submit" style="position:absolute;left:-999px;height:1px">
</td>
</tr>
</table>
</form>
</div>
<div class="search-div" style="display:none">
<form action="search.php" method="GET" class="advancedsearchform" id="search-notes">
<input type="hidden" name="searchtype" value="notes">
<table cellspacing=0 class="threed" style="width:680px;margin-left:auto;margin-right:0px;border-top:0px solid #bfbeb9">
<tr>
<td class="threed" style="width:9em">
Notes:
</td>
<td class="threed">
<?php search_row('notes'); ?>
</td></tr>
<tr>
<td class="threed" style="width:9em">
Search in:
</td>
<td class="threed" style="text-align:left">
<select name="category">
<option value="all">all categories</option>
<option value="0">!unassigned</option>
<?php
	foreach ($category_array as $category){

            print '<option value="'.htmlspecialchars($category['categoryID']).'"';
            if (isset($_SESSION['session_category']) && $_SESSION['session_category'] == $category['categoryID']) {
                    print ' selected';
            }
            print ">".htmlspecialchars($category['category'])."</option>\r\n";
	}
?>
</select>
</td></tr>
<tr>
<td class="threed">
Match:
</td>
<td class="threed">
<table border=0 cellspacing=0 cellpadding=0>
 <tr>
  <td class="select_span" style="line-height:16px">
   <input type="checkbox" name="whole_words" value="1" style="display:none" <?php if(isset($_SESSION['session_whole_words']) && $_SESSION['session_whole_words'] == 1) print ' checked'?>>
   <span class="ui-icon ui-icon-<?php print (isset($_SESSION['session_whole_words']) && $_SESSION['session_whole_words'] == 1) ? 'check' : 'close' ?>" style="float:left">
   </span>Whole words only&nbsp;
  </td>
  <td class="select_span" style="line-height:16px">
   <input type="checkbox" name="case" value="1" style="display:none" <?php print (isset($_SESSION['session_case']) && $_SESSION['session_case'] == 1) ? 'checked' : ''?>>
   <span class="ui-icon ui-icon-<?php print (isset($_SESSION['session_case']) && $_SESSION['session_case'] == 1) ? 'check' : 'close' ?>" style="float:left">
   </span>Match case&nbsp;
  </td>
 </tr>
</table>
</td></tr>
<?php
if (isset($_SESSION['auth'])) {
?>
<tr>
<td class="threed">
Save as:
</td>
<td class="threed">
<input type="text" name="searchname" style="width:99.5%">
</td></tr>
<?php
}
?>
<tr>
<td colspan="2" style="height:1px">
<input type="submit" style="position:absolute;left:-999px;height:1px">
</td>
</tr>
</table>
</form>
</div>
</div>